package com.proconsumer.controller;


import com.pojo.Role;
import com.pojo.Staff;
import com.service.RoleService;
import com.service.StaffService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/staff")
public class UserController {

    @Resource
    private RoleService roleService;

    @Resource
    private StaffService userService;

    @RequestMapping("/userList")
    @RequiresPermissions("userList")
    public String userList(Model model) {

        List<Staff> userList = userService.getAllStaffs();
        model.addAttribute("userList", userList);

        return "user/userList";
    }

    @RequestMapping("/userAdd")
    @RequiresPermissions("userAdd")
    public String userAdd(Model model) {
        List<Role> roleList = roleService.getAllRoles();
        model.addAttribute("roleList", roleList);
        return "user/userAdd";
    }

    @RequestMapping("/doUserAdd")
    @RequiresPermissions("userAdd")
    public String doUserAdd(Staff staff, int[] roles, Model model) {

        Staff userInfo = (Staff) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
        System.out.println(userInfo.getId() + "=============================");

        System.out.println(staff.toString());
        System.out.println(roles.length);

        int success = userService.addStaff(staff, roles);
        String msg = "";
        if (success == 1) {
            msg = "添加用户成功";
        } else {
            msg = "添加用户失败";
        }
        model.addAttribute("msg", msg);

        return "forward:/user/userAdd";
    }


    @GetMapping("/userEdit/{uid}")
    @RequiresPermissions("userEdit")
    public String userEdit(@PathVariable("uid") int uid,@PathVariable("id")int id, Model model) {
        Staff user = userService.getStaffById(uid);
        model.addAttribute("user", user);

        List<Role> roleList = roleService.getAllRoles();
        model.addAttribute("roleList", roleList);

        Staff u=userService.getId(id);
        model.addAttribute("user",u);

        return "user/userEdit";
    }

    @PostMapping("/doUserEdit")
    @RequiresPermissions("userEdit")
    public String doUerEdit(Staff staff, Model model) {
        String msg;
        int msge = userService.staffEdit(staff);
        if (msge == 1) {
            msg = "修改成功";
        } else {
            msg = "修改失败";
        }
        model.addAttribute("msg", msg);
        return "user/userEdit";
    }


    @RequestMapping("/userDelete")
    @ResponseBody
    public boolean userDelete(int id){
        return userService.staffDelete(id);
    }
}
